<template>
  <div class="customer">
    <ListTab v-if="!showMobilePage" show-header/>
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="table-box-title">
        <FilterInput
          ref="filterInput"
          v-model="filterForm"
          :filter-list="filterList"
          show-search-btn
          class="FilterTool"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty" />
        <div class="table-top-opeator-bar">
          <create-button v-if="hasRouteAuth('mengli:customer:create') || isAdmin" :add-name="'新增'" :create-link-name="'createMengliCustomer'" class="btn-right-item"/>
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 100px;">
        <u-table
          v-if="list.items.length > 0"
          ref="customerTableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @sort-change="sortMethod">
          <u-table-column align="left" label="客户名称" min-width="145">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.clientName && hasRouteAuth('mengli:customer:read')" :open-delay="800" placement="top-start" effect="dark">
                <div slot="content" style="max-width:200px;">{{ scope.row.clientName }}</div>
                <router-link
                  :to="{name: 'mengliCustomerDetail', params: { customerId: scope.row.id }}"
                  class="project-num">
                  <div class="ellipsis" style="color: #406EFF;">{{ scope.row.clientName }}</div>
                </router-link>
              </el-tooltip>
              <div v-else>{{ scope.row.clientName || '--' }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户类型" min-width="145" prop="clientType">
            <template slot-scope="scope">
              {{ scope.row.clientType | clientStatus }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" width="150">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="关联订单" min-width="120" prop="relatedOrderNum" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.relatedOrderNum | moneyFilter }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="备注" min-width="145">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" label-key="name" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" min-width="145">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.department | formatTag" label-key="name" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="80">
            <template slot-scope="scope">
              <CheckUserInfo :user-id="scope.row.createUserId" :label="scope.row.createName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}
            </template>
          </u-table-column>
          <u-table-column :align="operateAlign" :width="operateWidth" fixed="right" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" class="button-container">
                <div v-if="hasRouteAuth('mengli:customer:read')" class="button-text" @click="toDetail(scope.row)">查看</div>
                <el-dropdown trigger="click">
                  <div class="el-dropdown-link">
                    <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
                  </div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                    <el-dropdown-item :disabled="!hasRouteAuth('mengli:customer:edit')" style="width:80px;text-align: center" @click.native="toEdit(scope)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('mengli:customer:delete')" style="width:80px;text-align: center" @click.native="toDeleted(scope)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item v-if="hasRouteAuth('mengli:customer:read')" style="width:90px;text-align: center" @click.native="toDetail(scope.row)">
                  <div style="font-size: 14px">查看</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('mengli:customer:edit')" style="width:90px;text-align: center" @click.native="toEdit(scope)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('mengli:customer:delete')" style="width:90px;text-align: center" @click.native="toDeleted(scope)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <template v-if="showMobilePage">
          <FilterInput
            ref="filterInput"
            v-model="filterForm"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty" />
          <create-button v-if="hasRouteAuth('mengli:customer:create') || isAdmin" :add-name="'新增'" :create-link-name="'createMengliCustomer'" mobile-table class="mobile-create-btn"/>
        </template>
        <template v-else>
          <div style="flex:1"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { getMengliCustomerList, mengliCustomerDel } from '@/api/mengli';
import { getTagAll, getDepartmentAll } from '@/api/config';
import { TAG_MODULES } from '@/utils/const';
import TableAdaptive from '@/mixins/tableAdaptive';
import { standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { formatTag } from '@/filters/dept';
import mobileTable from '@/mixins/mobileTable';
import Title from '@/components/Title';
import CreateButton from '@/components/CreateButton';
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import TagSelect from '@/components/Common/tagSelect';
import setting from '@/assets/setting.png';

export default {
  filters: {
    standardFormat,
    moneyFilter,
    formatTag,
    clientStatus(type) {
      const obj = {
        '0': '公司',
        '1': '个人'
      };
      return obj[String(type)] || '--';
    }
  },
  components: { Title, CreateButton, EmptyPlaceholder, ListTab, TagSelect },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      setting,
      filterForm: {
        clientName: '',
        clientType: ''
        // departmentId: ''
      },
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true,
        totalAmount: '',
        amount: {}
      },
      perPage: 20,
      sortName: '',
      sortType: '',
      listLoading: true,
      page: 1,
      clientOption: [
        { value: -1, label: '全部' },
        { value: 1, label: '个人' },
        { value: 0, label: '公司' }
      ],
      tagTreeList: [],
      deptTreeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        { keyword: 'clientName', name: '客户名称', type: 'input' },
        // 下拉
        { keyword: 'clientType', name: '客户类型', type: 'select', options: this.clientOption },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        }
        // { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', strictly: true, options: this.deptTreeList }
      ];
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 150 : 192;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editMengliCustomer') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  created() {
    this.queryTagTreeList();
  },
  activated() {
    this.queryDeptTreeList();
    this.filterForm = !this.$route.meta.isChange ? {} : this.filterForm;
    this.fetchData();
  },
  deactivated() {
    window.onresize = null;
  },
  methods: {
    hasRouteAuth,
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.getMengliCustomerList();
    },
    fetchData() {
      if (!this.$route.meta.isChange) {
        this.queryEmpty();
      } else {
        this.getMengliCustomerList(this.list && this.list.items && this.list.items.length === 0);
      }
    },
    getMengliCustomerList(reset = false) {
      if (reset) this.page = 1;
      const { page, perPage } = this;
      const params = {
        page,
        perPage,
        clientName: this.filterForm.clientName,
        clientType: this.filterForm.clientType,
        tag: this.filterForm.tag,
        sortType: this.sortType || '',
        sortName: this.sortName || ''
        // departmentId: this.filterForm.departmentId
      };
      this.listLoading = true;
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      getMengliCustomerList(params).then(({ data }) => {
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    queryClick() {
      this.getMengliCustomerList(true);
    },
    queryEmpty() {
      this.filterForm = {};
      this.queryClick();
    },
    toDetail(row) {
      this.$router.push({
        name: 'mengliCustomerDetail',
        params: { customerId: row.id }
      });
    },
    toEdit(scope) {
      this.$router.push({
        name: 'editMengliCustomer',
        params: { customerId: scope.row.id }
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.MENGLI_CUSTOMER };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    toDeleted(scope) {
      const id = scope.row.id;
      this.$confirm('是否确定删除该萌力客户', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        mengliCustomerDel({ id }).then(res => {
          const { code, message } = res;
          if (code === 501) {
            this.$message.error(message);
            return false;
          }
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.getMengliCustomerList();
        }).catch(err => {
          // const { message = '出错啦，请再次尝试。' } = err;
          // this.$message.error(message);
          console.error(err);
        });
      }).catch(() => {});
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getMengliCustomerList(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getMengliCustomerList();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.customer {
  .lineheight32 {
    &::v-deep {
      .el-form-item__label,.el-form-item__content {
        line-height: 32px;
      }
    }
  }
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .table-box-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      margin-bottom: 20px;
      &::v-deep {
        .el-form-item{
          margin-bottom: 0;
        }
      }
    }
  }
}
.max-width-200 {
  max-width: 200px;
}
.button-container {
  display: flex;
  .border {
    display: block;
    padding-left:6px;
    margin-left: 6px;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>

